document.addEventListener('DOMContentLoaded', function () {
    var setToken = document.getElementById('setToken');
    var getToken = document.getElementById('getToken');
    var IconClick = document.getElementById('icon');
    var form = document.getElementById('form');
    setToken.addEventListener('click', () => {
        chromeSetLocalStorage()
    })
    getToken.addEventListener('click', () => {
        // 使用chrome.tabs.query查询匹配的标签页
        chrome.tabs.query({ url: `${form.elements['env']?.value}*` }, function(tabs) {
            if (tabs && tabs.length > 0) {
                // 输出匹配的标签页ID
                tokenFn({id: tabs[0].id}, (token)=>{
                    let val = `site3-f-ue  ${token}`
                    copyToClipboard(val)
                })
            } else {
                confirmFn()
            }
        });
    })
    IconClick.addEventListener('click', () => {
        chrome.windows.create({
            url: form.elements['env']?.value,
        },()=>{
            window.close();
        });
    })
})
function chromeSetLocalStorage() {
    var form = document.getElementById('form');
    chrome.tabs.query({ url: `${form.elements['env']?.value}*` }, function(tabs) {
        console.log(tabs)
        if (tabs && tabs.length > 0) {
            tokenFn({id: tabs[0].id},()=>{
                chrome.storage.local.get(['myData'], function (result) {
                    var token = ''
                    if(JSON.stringify(result) == '{}'){
                        confirmFn()
                    }else{
                        token = result.myData.value;
                    }
                    if (token) {
                        const port = form.elements['port']?.value || 8000
                        chrome.tabs.query({ url: `http://*:${port}/*` }, function(tabs) {
                            chrome.scripting.executeScript({
                                target: { tabId: tabs[0].id },
                                function: (token) => {
                                    // 在标签页中设置LocalStorage数据
                                    localStorage.setItem('site3-f-ue', token);
                                },
                                args: [token]
                            }).then(() => {
                                chrome.tabs.query({ url: `${form.elements['env']?.value}*` }, function(zhgdTabs) {
                                    if(zhgdTabs.length){
                                        if (tabs[0].url.includes('/#/')) {
                                            var address = tabs[0].url.split('/#/')[0];
                                            var zhgdUrl = zhgdTabs[0].url.split('/console')[1];
                                            chrome.tabs.update(tabs[0].id, { url: `${address}/#/console${zhgdUrl}` }, function(tab) {
                                                chrome.notifications.create({
                                                    type: 'basic',
                                                    iconUrl: './sl1.png',
                                                    title: 'Chrome插件',
                                                    message: '设置成功'
                                                });
                                            });
                                        }else{
                                            chrome.notifications.create({
                                                type: 'basic',
                                                iconUrl: './sl1.png',
                                                title: 'Chrome插件',
                                                message: '设置路由失败，未检测到您的路由,请手动拼接！'
                                            });
                                        }
                                    }else{
                                        chrome.notifications.create({
                                            type: 'basic',
                                            iconUrl: './sl1.png',
                                            title: 'Chrome插件',
                                            message: '设置路由失败，您似乎为打开智慧工地测试平台！'
                                        });
                                    }
                                })
                                
                            }).catch((error) => {
                                console.error('chrome插件: token设置失败 ', error);
                            })
                        })
                    } else {
                        confirmFn()
                    }
                });
            })
        } else {
            confirmFn()
        }
    })
}

function tokenFn(tab, fn){
    chrome.scripting.executeScript({
        target: { tabId: tab.id },
        function: function () {
            var localStorageData = JSON.stringify(localStorage);
            return localStorageData;
        }
    }).then((result) => {
        let session = JSON.parse(result[0].result)
        myData.value = session['site3-f-ue']
        chrome.storage.local.set({ myData: myData });
        if(fn){
            fn(myData.value)
        }
    }).catch((error) => {
        console.error('Error retrieving local storage data:', error);
    });
}

function confirmFn(){
    var mymessage = confirm('chrome插件:token为空, 是否打开智慧工地(预发)测试获取token')
    if(mymessage){
        var form = document.getElementById('form');
        chrome.tabs.create({
            url: form?.elements['env']?.value || 'https://digitalconstruction-pre.cscec3b-iti.com/'
        })
    }else{
        console.warn('chrome插件: token设置失败')
    }
}

function copyToClipboard(text) {
    if (!text) return;
    // 使用 navigator.clipboard.writeText() 方法
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text)
        .then(() => {
            console.log('Text copied to clipboard');
        })
        .catch(err => {
            console.error('Error copying text to clipboard: ', err);
        });
        window.close();
    } else {
        // 寻找可编辑的 textarea 元素并使用旧方法
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        document.body.appendChild(textarea);
        textarea.focus();
        textarea.select();

        try {
            document.execCommand('copy');
            console.log('Text copied to clipboard');
        } catch (err) {
            console.error('Error copying text to clipboard: ', err);
        }

        document.body.removeChild(textarea);
        window.close();
    }
    chrome.notifications.create({
        type: 'basic',
        iconUrl: './sl1.png',
        title: 'Chrome插件',
        message: '复制成功'
    });
}
